package com.lanyam.travel.base.config;


import com.lanyam.travel.base.entity.base.BaseResponse;
import com.lanyam.travel.base.entity.base.ErrorResponseBuilder;
import com.lanyam.travel.base.utils.LogUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import static com.alibaba.fastjson.JSON.toJSONString;

/**
 * @author KingTang
 * @date   2019/12/20
 */
@Configuration
public class CustomerViewResolver extends SimpleMappingExceptionResolver {

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
                                              Object handler, Exception ex) {
        try {
            BaseResponse result = new ErrorResponseBuilder().exception(ex).build();
            response.setHeader("Content-type", "application/json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(toJSONString(result));
            writer.flush();
        } catch (IOException e) {
            LogUtils.logger.debug("catchException", e);
        }
        return null;
    }


}
